package cn.tedu.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 案例: 跑步比赛
 * 运动员到了起跑线
 * 等运动员到齐之后, 发号枪响, 每个运动员都跑出去
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cb = new CyclicBarrier(6);
        new Thread(new Runner(cb), "1号").start();
        new Thread(new Runner(cb), "2号").start();
        new Thread(new Runner(cb), "3号").start();
        new Thread(new Runner(cb), "4号").start();
        new Thread(new Runner(cb), "5号").start();
        new Thread(new Runner(cb), "6号").start();
    }
}

class Runner implements Runnable {
    private CyclicBarrier cyclicBarrier;

    public Runner(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        try {
            // 模拟每一个运动员到起跑线的时间不一样
            Thread.sleep((long) Math.random() * 10000);
            System.out.println(name + "运动员到了起跑线");
            // 会让当前线程陷入阻塞, 同时计数减少一个
            cyclicBarrier.await();
            // 运动员到了之后应该等待, 等所有的运动员都到齐了之后才能往外跑
            System.out.println(name + "运动员起跑了");
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        } catch (BrokenBarrierException brokenBarrierException) {
            brokenBarrierException.printStackTrace();
        }
    }
}
